package com.beiing.tianshuai.tianshuai.app;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.PointF;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.ImageView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.nim.chatroom.ChatRoomSessionHelper;
import com.beiing.tianshuai.tianshuai.nim.config.preference.UserPreferences;
import com.beiing.tianshuai.tianshuai.nim.contact.ContactHelper;
import com.beiing.tianshuai.tianshuai.nim.event.DemoOnlineStateContentProvider;
import com.beiing.tianshuai.tianshuai.nim.mixpush.DemoMixPushMessageHandler;
import com.beiing.tianshuai.tianshuai.nim.mixpush.DemoPushContentProvider;
import com.beiing.tianshuai.tianshuai.nim.redpacket.NIMRedPacketClient;
import com.beiing.tianshuai.tianshuai.nim.session.NimDemoLocationProvider;
import com.beiing.tianshuai.tianshuai.nim.session.SessionHelper;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.lzy.ninegrid.NineGridView;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.UIKitOptions;
import com.netease.nim.uikit.business.contact.core.query.PinYin;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.mixpush.NIMPushClient;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zxy.tiny.Tiny;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

import cn.jpush.android.api.JPushInterface;
import cn.magicwindow.Session;

/**
 * Created by magikliu on 2017/7/12.
 */

public class MyApplication extends Application {

    private static final String TAG = "MyApplication";
    private RequestOptions requestOptions;
    private RequestOptions mRequestOptionsNoOverride;
    private RequestOptions mLongImgRequestOptions;
    private RequestOptions mLongImgThumbRequestOptions;
    private Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        initBugly();
        initDir();
        initNineGridView();

        JPushInterface.setDebugMode(AppConstant.IS_DEBUG);
        JPushInterface.init(this);

        initTiny();
        new DataManager(this);
        registerWXAPI();

        // 初始化魔创Session
        Session.setAutoSession(this);

        // 登陆及初始化网易云信
        DemoCache.setContext(mContext);
        NIMClient.init(mContext, getLoginInfo(), NimSDKOptionConfig.getSDKOptions(mContext));
        // 以下逻辑只在主进程初始化时执行
        if (NIMUtil.isMainProcess(this)) {

            // 注册自定义推送消息处理，这个是可选项
            NIMPushClient.registerMixPushMessageHandler(new DemoMixPushMessageHandler());

            // 初始化红包模块，在初始化UIKit模块之前执行
            NIMRedPacketClient.init(this);
            // init pinyin
            PinYin.init(this);
            PinYin.validate();
            // 初始化UIKit模块
            initUIKit();
            // 初始化消息提醒
            NIMClient.toggleNotification(UserPreferences.getNotificationToggle());
            // 云信sdk相关业务初始化
            NIMInitManager.getInstance().init(true);
        }
    }

    // 返回登陆用户信息
    private LoginInfo getLoginInfo() {
        String userAccount = UserInfoBean.getUid(mContext);
        String userToken = UserInfoBean.getUserToken(mContext);

        if (!TextUtils.isEmpty(userAccount) && !TextUtils.isEmpty(userToken)) {
            return new LoginInfo(userAccount, userToken);
        } else {
            return null;
        }
    }

    private void initUIKit() {
        // 初始化
        NimUIKit.init(this, buildUIKitOptions());

        // 设置地理位置提供者。如果需要发送地理位置消息，该参数必须提供。如果不需要，可以忽略。
        NimUIKit.setLocationProvider(new NimDemoLocationProvider());

        // IM 会话窗口的定制初始化。
        SessionHelper.init();

        // 聊天室聊天窗口的定制初始化。
        ChatRoomSessionHelper.init();

        // 通讯录列表定制初始化
        ContactHelper.init();

        // 添加自定义推送文案以及选项，请开发者在各端（Android、IOS、PC、Web）消息发送时保持一致，以免出现通知不一致的情况
        NimUIKit.setCustomPushContentProvider(new DemoPushContentProvider());

        NimUIKit.setOnlineStateContentProvider(new DemoOnlineStateContentProvider());
    }

    private UIKitOptions buildUIKitOptions() {
        UIKitOptions options = new UIKitOptions();
        // 设置app图片/音频/日志等缓存目录
        options.appCacheDir = NimSDKOptionConfig.getAppCacheDir(this) + "/app";
        return options;
    }

    private void registerWXAPI() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(mContext, null);
        msgApi.registerApp(AppConstant.WX_APP_ID);
    }

    // 腾讯Bugly异常上报机制
    private void initBugly() {
        // 获取当前包名
        String packageName = mContext.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(mContext);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        CrashReport.initCrashReport(mContext, "2936a7e2e7", false, strategy);
        // 设置上报的用户id
        String uid = UserInfoBean.getUid(mContext);
        if (!TextUtils.isEmpty(uid)) {
            CrashReport.setUserId(uid + "#" + UserInfoBean.getNickName(mContext));
        } else {
            CrashReport.setUserId("游客");
        }
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    private void initDir() {
        String dir = Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/";
        File mainDir = new File(dir);
        if (!mainDir.exists()) {
            if (!mainDir.mkdirs()) {
                LogUtils.e("创建文件夹失败", TAG);
            }
        }
    }

    /**
     * 初始化9宫格视图
     */
    private void initNineGridView() {
        NineGridView.setImageLoader(new NineGridView.ImageLoader() {
            @Override
            public void onDisplayImage(Context context, ImageView imageView, String url, int width, int height) {
                if (requestOptions == null) {
                    requestOptions = new RequestOptions()
                            .override(width, height)
                            .placeholder(R.color.gray_light)
                            //检查来修改当前对象
                            .dontAnimate()
                            //磁盘缓存
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .fitCenter();
                }
                Glide.with(context)
                        .load(url)
                        .apply(requestOptions)
                        .into(imageView);
            }

            /**
             * 只有长图的时候才复用requestOptions
             * @param context   上下文
             * @param imageView 需要展示图片的ImageView
             * @param url       图片地址
             * @param width
             * @param height
             * @param cut
             */
            @Override
            public void onDisplayImage(Context context, ImageView imageView, String url, int width, int height, int cut) {
                //requestOptions=null;
                if (mLongImgThumbRequestOptions == null) {
                    mLongImgThumbRequestOptions = new RequestOptions()
                            .placeholder(R.color.gray_light)
                            //检查来修改当前对象
                            .dontAnimate()
                            //磁盘缓存
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .centerCrop();
                }
                Glide.with(context)
                        .load(url)
                        .apply(mLongImgThumbRequestOptions)
                        .into(imageView);
            }

            @Override
            public void onDisplayImage(Context context, ImageView imageView, String url) {
                if (mRequestOptionsNoOverride == null) {
                    mRequestOptionsNoOverride = new RequestOptions()
                            .placeholder(R.drawable.img_loading_background)
                            .diskCacheStrategy(DiskCacheStrategy.ALL);
                }
                Glide.with(context)
                        .load(url)
                        .apply(mRequestOptionsNoOverride)
                        .into(imageView);
            }

            /**
             * 初始化九宫格长图视图
             * @param context   上下文
             * @param imageView 长图控件
             * @param url       图片地址
             */
            @Override
            public void onDisplayImage(Context context, final SubsamplingScaleImageView imageView, final String url) {
                if (mLongImgRequestOptions == null) {
                    mLongImgRequestOptions = new RequestOptions()
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .placeholder(R.drawable.img_loading_background)
                            .centerCrop();
                }

                //开启控件自定义设置
                imageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);

                try {
                    Glide.with(mContext).asBitmap()
                            .load(url)
                            .apply(mLongImgRequestOptions)
                            .into(new SimpleTarget<Bitmap>() {
                                @SuppressLint("StaticFieldLeak")
                                @Override
                                public void onResourceReady(@NonNull final Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    new AsyncTask<Void, Void, String>() {
                                        @Override
                                        protected String doInBackground(Void... voids) {
                                            String resultPath = null;
                                            File file = new File(Environment.getExternalStorageDirectory(), "TianShuai/天率校园/");
                                            if (!file.exists()) {
                                                file.mkdirs();
                                            }
                                            try {
                                                File tempFile = File.createTempFile("tsimg_" + System.currentTimeMillis(), null, file);
                                                FileOutputStream fileOutputStream = null;
                                                try {
                                                    fileOutputStream = new FileOutputStream(tempFile);
                                                    resource.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
                                                    resultPath = tempFile.getAbsolutePath();
                                                } catch (FileNotFoundException e) {
                                                    e.printStackTrace();
                                                } finally {
                                                    try {
                                                        if (fileOutputStream != null) {
                                                            fileOutputStream.close();
                                                        }
                                                        tempFile.deleteOnExit();
                                                    } catch (IOException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                            return resultPath;
                                        }

                                        @Override
                                        protected void onPostExecute(String s) {
                                            if (!TextUtils.isEmpty(s)) {
                                                float initImageScale = getInitImageScale(s);
                                                //最大显示比例
                                                imageView.setMaxScale(initImageScale + 4.0f);
                                                imageView.setMinScale(1.0f);
                                                imageView.setImage(
                                                        ImageSource.uri(s),
                                                        new ImageViewState(initImageScale, new PointF(0, 0), 0)
                                                );
                                            }
                                        }
                                    }.execute();
                                }
                            });
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.i(TAG, "网络加载失败" + e);
                }
            }

            @Override
            public Bitmap getCacheImage(String url) {
                return null;
            }
        });
    }

    /**
     * 计算出图片初次显示需要放大倍数
     *
     * @param imagePath 图片的绝对路径
     */
    public float getInitImageScale(String imagePath) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, opt);
        float scale;
        //屏幕宽度
        WindowManager wm = (WindowManager) this.getSystemService(WINDOW_SERVICE);
        Point point = new Point();
        if (wm != null) {
            wm.getDefaultDisplay().getSize(point);
        }
        int width = point.x;
        // 拿到图片的宽和高
        int dw = opt.outWidth;

        if (dw > width) {
            scale = dw / (float) width;
        } else {
            scale = (float) width / dw;
        }

        return scale;
    }

    private void initTiny() {
        Tiny.getInstance().debug(AppConstant.IS_DEBUG);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

}
